<?php

namespace LhpAmis\util;

use think\console\Input;
use think\console\Output;

/**
 * 扩展安装更新及卸载的资源文件操作
 * 1. 安装更新时,复制assets/ueditor文件到/public/static/bingher/ueditor/
 * 2. 卸载时,删除/public/static/bingher/ueditor/,如果/public/static/bingher为空也一并删除了
 */
class Resources
{
    /**
     * 安装动作
     *
     * @param bool $overWrite 是否覆盖,默认:true
     *
     * @return boolean
     */
    public static function install(Input $input, Output $output, bool $overWrite = true)
    {
        try {
            $assets = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR;
            $static = root_path() . 'public' . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'lhpAmis' . DIRECTORY_SEPARATOR;
            $res = FileUtil::copyDir($assets, $static, $overWrite);
            if (!$res) {
                $output->writeln('assets:资源安装失败!');
            } else {
                $output->writeln('assets:资源安装成功!');
            }
        } catch (\Throwable $th) {
            //throw $th;
            // dump($th->getMessage());
            // dump($th->getTraceAsString());
        }
        return $res;
    }

    public static function plugins(Input $input, Output $output, bool $overWrite = true)
    {
        try {
            $assets = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Plugin' . DIRECTORY_SEPARATOR;
            $static = root_path() . 'public' . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'lhpAmis' . DIRECTORY_SEPARATOR . 'plugin' . DIRECTORY_SEPARATOR;
            $scandir_plugins = scandir($assets);

            foreach ($scandir_plugins as $value) {
                if ($value == '.' || $value == '..') {
                    continue;
                }
                $file = $assets . $value . DIRECTORY_SEPARATOR . 'assets';
                $file_static = $static . $value;
                if (is_dir($file)) {
                    $res = FileUtil::copyDir($file, $file_static, $overWrite);
                    if (!$res) {
                        $output->writeln($value . ':资源安装失败');
                    } else {
                        $output->writeln($value . ':资源安装成功');
                    }
                }
            }
        } catch (\Throwable $th) {
            $output->writeln($value . ':资源安装失败');
        }
    }

    /**
     * 卸载操作
     *
     * @return boolean
     */
    public static function uninstall(Input $input, Output $output)
    {
        try {
            $static = root_path() . 'public' . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'lhpAmis' . DIRECTORY_SEPARATOR;
            if (FileUtil::unlinkDir($static)) {
                $output->writeln('assets:资源删除成功!');
            } else {
                $output->writeln('assets:资源删除失败,请手动删除' . $static);
            }
        } catch (\Throwable $th) {
            $output->writeln('assets:资源删除失败,请手动删除' . $static);
            // dump($th->getMessage());
            // dump($th->getTraceAsString());
        }
    }
}
